﻿using LibNiconico.NiconicoApi.Extentions;
using LibNiconico.NiconicoApi.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace LibNiconico.NiconicoApi.Lives.Broadcast
{
    internal class NicoLiveBroadcastCreateConfirmQueryInfo : NicoMultPartPostAble
    {
        private NicoLiveBroadcastCreateConfirmQueryInfo()
        {
        }

        

        internal override byte[] AsPostData()
        {
            return Encoding.UTF8.GetBytes(this.FormData.ToString());
        }

        internal override string AsPath()
        {
            return "editstream";
        }

        internal override string AsQuery()
        {
            return "";
        }

        internal string ErrorMessage { get; private set; }

        internal static NicoLiveBroadcastCreateConfirmQueryInfo CreateFrom(XDocument requestDocument)
        {
            var query = new NicoLiveBroadcastCreateConfirmQueryInfo();

            var formNodes = from node in requestDocument.Descendants()
                                  where node.Name == "form" && node.Attribute("id") != null && node.Attribute("id").Value == "esf"
                                  select node;


            if (formNodes.Count() > 0)
            {

                var formRootNode = formNodes.First();
                var formInputs = from formNode in formRootNode.Descendants()
                                 where formNode.Name == "input"
                                 select formNode;

                

                if (formInputs != null && formInputs.Count() > 0)
                {

                    var inputs = from inputNode in formInputs
                                 where inputNode.Attribute("name") != null && inputNode.Attribute("name").Value != "submit_back"
                                 select new KeyValuePair<string, string>(inputNode.Attribute("name").Value, inputNode.Attribute("value").Value);


                    query.FormData.AddRange(inputs);
                    return query;
                }
            }

            var errorNodes = from errorNode in requestDocument.Descendants("li")
                             where (string)errorNode.Attribute("id") == "error_message"
                             select errorNode.Value;

            if (errorNodes.Count() > 0)
            {
                query.ErrorMessage = errorNodes.First();
            }

            return query;
            

        }
    }
}
